/** 是否激活 */
export const useActivated = () => {
  const isActivated = ref(false);

  onMounted(() => {
    isActivated.value = true;

    onActivated(() => {
      isActivated.value = true;
    });
  });

  onDeactivated(() => {
    isActivated.value = false;
  });

  onBeforeUnmount(() => {
    isActivated.value = false;
  });

  return {
    isActivated,
  };
};

/** 激活时执行时间 */
export const useActivatedExec = (callback: () => void) => {
  const { isActivated } = useActivated();
  watch(
    isActivated,
    (value) => {
      if (value) {
        callback();
      }
    },
    {
      immediate: true,
    },
  );
};

/** 激活时监听事件 */
export const useActivatedEvent = (bind: () => void, unbind: () => void) => {
  const { isActivated } = useActivated();
  watch(
    isActivated,
    (value) => {
      if (value) {
        bind();
      } else {
        unbind();
      }
    },
    {
      immediate: true,
    },
  );
};
